#include "qhtmlrenderer.h"
#include "htmltext.h"
#include "organizedtextcontext.h"
#include <QtWebKit/QWebView>
#include <Qt/qstring.h>

QHtmlRenderer::QHtmlRenderer():
        _pixmap(0)
{
}

QHtmlRenderer::~QHtmlRenderer(){
}

void QHtmlRenderer::render(HtmlText * text){
    XCHAR * str = text->getText();
    QString * qStr = new QString(str);
    QWebView * view = new QWebView();
    view->setHtml(*qStr);
    view->render(_pixmap);
}

void QHtmlRenderer::render(TextDialog * dialog, QPainter * painter, int x, int y, int space){
    TextLabel * textLabel = dialog->getTextLabel();
    OrganizedTextContext * context = (OrganizedTextContext *)textLabel->getContext();
    int currChar = dialog->getCurrentIndex();
    int currPage = dialog->getCurrentPage();
    std::vector<int> * pages = context->getPages();
    int startIndex = 0;
    if( currPage )
        startIndex = (*pages)[currPage - 1] + 1;
    std::vector<int> * lines = context->getLines();
    int currLine = 0;
    if( startIndex ){
        for(int i = 0; i < lines->size(); ++i ){
            if( startIndex - 1 == (*lines)[i] ){
                currLine = i + 1;
                break;
            }
        }
    }
    int endLine = 0;
    for(int i = 0; i < lines->size(); ++i)
        if( (*lines)[i] >= currChar ){
            endLine = i;
            break;
        }
    for(int i = currLine; i <= endLine; ++i){
        int startChar = 0;
        if( i )
            startChar = (*lines)[i - 1] + 1;
        int endChar = (*lines)[i];
        if( i == endLine )
            endChar = currChar;
        XCHAR * str = textLabel->getSubstring(startChar, endChar + 1);
        QString qStr(str);
        painter->drawText(x, y + space * ( i - currLine + 1 ), qStr);
    }
}
